import {Input, Icon, Tree} from 'antd';
// import Icon from '../../../_antd1.11.2/icon'
// import Input from '../../../_antd1.11.2/input'
// import Tree from '../../../_antd1.11.2/tree'
const TreeNode = Tree.TreeNode;
import cloneDeep from 'lodash/cloneDeep'
import isArray from 'lodash/isArray'
import WeaTools from '../../wea-tools'

let that = {};

export default class WeaTreeHr extends React.Component {
    constructor(props) {
        super(props);
        const {dataUrl,otherPara,prefix,topPrefix,dataKey,isMult,ids,names,defaultExpandedKeys} = props;
        let idArr = ids?ids.split(","):[];
        let nameArr = names?names.split(","):[];
         for(let i=0;i<idArr.length;i++) {
            idArr[i] = prefix+idArr[i];
        }
        this.state = {
            treeData: [],
            prefix:prefix,
            dataKey:dataKey,
            topPrefix:topPrefix,
            isMult:isMult,
            ids:idArr,
            names:nameArr,
            expandedKeys:defaultExpandedKeys,
            defaultExpandedKeys:defaultExpandedKeys
        }
        that = this;
    }
    componentDidMount() {
        const{treeData,} = this.props;
        generateData(treeData.datas)
        this.setState({
            treeData: objToArray(treeData.datas),
        });

    }
    componentWillReceiveProps(nextProps) {
        const{treeData,componyParam,defaultExpandedKeys} = this.props;
        if(this.props.treeData !== nextProps.treeData){
            generateData(nextProps.treeData.datas);
            this.setState({
                expandedKeys:nextProps.defaultExpandedKeys,
                treeData: objToArray(nextProps.treeData.datas),
            });
        }
        if(defaultExpandedKeys !== nextProps.defaultExpandedKeys){
            this.setState({defaultExpandedKeys:nextProps.defaultExpandedKeys})
        }
    }
   onSelect(info,e) {
        const nodes = e.selectedNodes;
        const nowNode = e.node;
        const eventKey = e.node.props.eventKey;
        this.setTheDatas(nodes, eventKey);
    }
    onExpandChange(expandedKeys, nodeObj){
        this.setState({expandedKeys:expandedKeys})
    }
    setTheDatas(nodes, key) {
        const{recentUrl}=this.props;
        let idArr = [];
        let nameArr = [];
        for(let i=0; i<nodes.length; i++) {
            const node = nodes[i].props;
            if(key.indexOf("resource") > -1){
                idArr.push(node.id);
                nameArr.push(node.lastname);
            }
        }
        // let newIdArr = [...new Set(idArr)];
        // let newNameArr = [...new Set(nameArr)];
        let newIdArr = [];
        let newNameArr = [];
        jQuery.each(idArr, function(i, el){
            if(jQuery.inArray(el, newIdArr) === -1) newIdArr.push(el);
        });
        jQuery.each(nameArr, function(i, el){
            if(jQuery.inArray(el, newNameArr) === -1) newNameArr.push(el);
        });

        let ids = newIdArr.join(",");
        let names = newNameArr.join(",");
        key.indexOf("resource") > -1 && this.props.setData && this.props.setData(ids,names);
    }
    onLoadData(treeNode) {
        let _this = this;
        const {dataUrl, isAccount, virtualtype} = this.props;
        const {eventKey,treeKey,id,type} = treeNode.props;
        const params = {
            type: type,
            id: id
        }
        if (isAccount) params['isNoAccount'] = 1;
        if (virtualtype) params['virtualtype'] = virtualtype;
        return new Promise((resolve)=> {
            WeaTools.callApi(dataUrl, 'GET', params).then((datas)=> {
                const treeData = [..._this.state.treeData];
                getNewTreeData(treeData, treeKey, generateTreeNodes(datas, treeNode), 3);
                _this.setState({treeData});
                resolve();
            });
        });
    }

    render() {
        const {isMult,ids,treeData,defaultExpandedKeys} = this.state;
        // console.log("defaultExpandedKeys",defaultExpandedKeys)
        const {icon} = this.props;
        // console.log("this.state.treeData",this.state.treeData);
        const loop = data => data.map((item) => {
            let title=null;
            if(item.type == "com"){
                title = <div>{icon}{item.lastname}<span style={{fontSize:"12px",color:"#979797"}}>{/*人数占位*/}</span></div>;
            }else if(item.type == "subcom"){
                title = <div><i className="icon-process-scene"/>{item.lastname}</div>;
            }else if(item.type == "dept"){
                title = <div><i className="icon-mail-folder"/> {item.lastname}</div>;
            }else if(item.type == "resource"){
                title = <div style={{fontSize:"12px"}}><img className="wea-tree-hr-portrait" src={item.icon} alt="img"/><span style={{paddingLeft:10}}>{item.lastname}</span>  <span style={{color:"#929390",paddingLeft:10}}>{item.jobtitlename}</span></div>;
            }else{
                title = <div><i className="icon-process-scene"/> {item.lastname}</div>
            }

            if (item.children && item.children.length>0) {
                // console.log("item.treeKey",item.treeKey);
                for(let i =0;i<item.children.length;i++){
                    item.children[i].treeKey = `${item.treeKey}-${item.children[i].nodeid}`;
                }
                // console.log("item",item);
                return <TreeNode title={title}
                            lastname={item.lastname}
                            jobtitlename={item.jobtitlename}
                            key={item.treeKey}
                            id={item.id}
                            treeKey={item.treeKey}
                            isLeaf={item.isLeaf}
                            type={item.type}>
                        {loop(item.children)}
                        </TreeNode>
            }
            return <TreeNode title={title}
                        lastname={item.lastname}
                        jobtitlename={item.jobtitlename}
                        key={item.treeKey}
                        id={item.id}
                        treeKey={item.treeKey}
                        isLeaf={item.isLeaf}
                        type={item.type}
                        />
        });
        const treeNodes = loop(this.state.treeData);
        return (
            <Tree className="my-Tree"
                clickNodeExpandChildren
                defaultExpandedKeys={defaultExpandedKeys}
                expandedKeys={this.state.expandedKeys}
                onSelect={this.onSelect.bind(this)}
                loadData={this.onLoadData.bind(this)}
                checkable={isMult}
                multiple={isMult}
                selectedKeys={ids}
                checkedKeys={ids}
                needExpandChildren
                onExpand={this.onExpandChange.bind(this)}>
            {treeNodes}
            </Tree>
        )
    }
};

function objToArray(obj) {
    if (!isArray(obj)) {
        let arr = [];
        arr.push(obj);
        obj = arr;
    }
    return obj;
}

function generateData(data, level = 1) {
    const {topPrefix} = that.state;
    if (!isArray(data)) {
        data.isLeaf = data.isParent === "false";
        if (level == 1) data.treeKey = `${topPrefix}0-${data.nodeid}`;
        if (data.children && data.children.length > 0) generateData(data.children, level+1);
    } else {
        data.forEach((item) => {
            if (level == 1) item.isLeaf = item.isParent === "false";
            if (item.children && item.children.length > 0) generateData(item.children, level+1);
        })
    }
}

function generateTreeNodes(data,treeNode) {
    let arr = new Array();
    const {topPrefix} = that.state;
    if(!treeNode){
        arr.push({
            id:data.id,
            lastname:data.lastname,
            nodeid:data.nodeid,
            jobtitlename:data.jobtitlename,
            treeKey:`${topPrefix}0-${data.nodeid}`,
            icon:data.icon,
            isLeaf: !data.isParent || data.isParent === "false",//isLeaf:data.children.length === 0,
            children:data.children,
            open:data.open,
            type:data.type,
        });
    }else{
        const loop = datas =>{
            for (let i=0;i<datas.length;i++) {
                const data = datas[i];
                const {treeKey,id} = treeNode.props;
                arr.push({
                    id:data.id,
                    lastname:data.lastname,
                    nodeid:data.nodeid,
                    jobtitlename:data.jobtitlename,
                    treeKey:`${treeKey}-${data.nodeid}`,
                    icon:data.icon,
                    isLeaf: !data.isParent || data.isParent === "false",//isLeaf:data.children.length === 0,
                    children:data.children,
                    open:data.open,
                    type:data.type,
                });
            }
        }
        loop(data.datas);
    }
    return arr;
}

function getNewTreeData(treeData, curKey, child, level) {
    // console.log(treeData, curKey, child, level);
    let hrData = new Array();
    const findData = data => data.forEach(item => {
        if (item.children && !!item.open) {
            findData(item.children);
        }else if(!item.open){
            hrData.push(item);
        }
    });
    findData(treeData);

    const loop = (data) => {
        data.forEach((item) => {
            if ((curKey+"-").indexOf(item.treeKey+"-") === 0) {
                if (item.children && item.children.length>0) {

                    loop(item.children);
                } else {
                    item.children = child;
                }
            }else{
            }
        });
    };

    loop(hrData);

}
